package org.yaac.server.util;

import java.math.BigDecimal;

/**
 * @author Max Zhu (thebbsky@gmail.com)
 *
 */
public class BigDecimalUtil {

	/**
	 * @param input
	 * @return
	 */
	public static BigDecimal of(Number input) {
		if (input instanceof Integer) {
			return new BigDecimal((Integer)input);
		} else if (input instanceof Byte) {
			return new BigDecimal((Byte)input);
		} else if (input instanceof Short) {
			return new BigDecimal((Short)input);
		} else if (input instanceof Long) {
			return new BigDecimal((Long)input);
		} else if (input instanceof Float) {
			return new BigDecimal((Float)input);
		} else if (input instanceof Double) {
			return new BigDecimal((Double)input);
		} else if (input instanceof BigDecimal) {
			return (BigDecimal) input;
		} else {
			throw new IllegalArgumentException("Unsupported type " + input.getClass());
		}
	}
	
	public static Number toDatastoreNumber(BigDecimal bd) {
		if (bd.longValue() == bd.doubleValue()) {
			return Long.valueOf(bd.longValue());
		} else {
			return Double.valueOf(bd.doubleValue());
		}
		
		// don't know why this doesn't work, probably some autoboxing issue
//		return bd.longValue() == bd.doubleValue() ? bd.longValue() : bd.doubleValue();
	}
}
